import json
import redis
import pymysql

def main():
    
    r = redis.Redis(host = 'localhost',port = 6379, decode_responses = True)
    
    db = pymysql.connect(host = '192.168.43.32', user = 'jack', password = 'jack123456', db = 'goodread', charset='utf8')
    
    cursor = db.cursor()
    
    while True:
        
        source, data = r.blpop(['goodread:items'])
        print(source)
        try:
            item = json.loads(data)
            book = dict(item)
            print(book)
            keys = ','.join(book.keys())
            #print(keys)
            values = ','.join(['%s']*len(book))
            #print(values)
            sql = 'insert into books(%s) values(%s)'%(keys,values)
            #print(sql)
            cursor.execute(sql,tuple(book.values()))
            db.commit()
            print('Import into MYSQL successful')
        except Exception as err:
            
            db.rollback()
            print("SQL Execute Error :", err)
    
if __name__ == '__main__':
    main()
